package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.entity.dto.shoppingcart.ShoppingCartDto;
import com.itheima.entity.dto.shoppingcart.ShoppingCartSubDto;
import com.itheima.entity.vo.shoppingcart.ShoppingCartAddVo;
import com.itheima.entity.vo.shoppingcart.ShoppingCartListVo;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author huangzelnag
 * @create 2022-05-12
 */

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartControllrer {
    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;


    @GetMapping("list")
    public R getShoppingCartList(){
        List<ShoppingCartListVo> shoppingCartList = shoppingCartService.getShoppingCartList();

        return R.success(shoppingCartList);
    }

    /**
     * 加入购物车
     * @param shoppingCartDto
     * @return
     */
    @PostMapping("add")
    public R addShoppingCart(@RequestBody ShoppingCartDto shoppingCartDto ){
        //接口防刷
        String currentId = TokenHolder.getCurrentId();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(currentId+"addShoppingCart","",1L, TimeUnit.SECONDS);
        if(!flag){
            return R.error("1s 内请勿频繁请求");
        }
          ShoppingCartAddVo shoppingCartAddVo = shoppingCartService.addShoppingCart(shoppingCartDto);
        return R.success(shoppingCartAddVo);
    }


    /**
     * 删除购物车商品
     * @return
     */
    @PostMapping("sub")
    public R delShoppingCartSub(@RequestBody ShoppingCartSubDto shoppingCartSubDto){


        shoppingCartService.delShoppingCartSub(shoppingCartSubDto);


        return R.success("");
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("clean")
    public R delShoppingCart(){

    Boolean flag =    shoppingCartService.delShoppingCart();

    return R.success("");
    }


}
